import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';

const AuthCallback = () => {
  const navigate = useNavigate();
  const { getLink } = useLocalizedLink();
  const [error, setError] = useState('');

  useEffect(() => {
    const handleCallback = async () => {
      try {
        // Check if user is authenticated
        const result = await authService.getCurrentUser();
        
        if (result.success) {
          // Successfully authenticated, redirect to dashboard
          navigate(getLink('/dashboard'));
        } else {
          // Authentication failed
          setError('Authentication failed');
          setTimeout(() => {
            navigate(getLink('/login'));
          }, 2000);
        }
      } catch (err) {
        console.error('Auth callback error:', err);
        setError('Authentication failed');
        setTimeout(() => {
          navigate(getLink('/login'));
        }, 2000);
      }
    };

    handleCallback();
  }, [navigate, getLink]);

  return (
    <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 transition-colors duration-300">
      <div className="text-center">
        {error ? (
          <div>
            <div className="text-red-600 dark:text-red-400 text-lg mb-2">
              {error}
            </div>
            <p className="text-gray-600 dark:text-gray-400">
              Redirecting to login...
            </p>
          </div>
        ) : (
          <div>
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#00d4ff] mb-4"></div>
            <p className="text-gray-900 dark:text-white text-lg">
              Completing authentication...
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default AuthCallback;
